// packageC/pages/takeoutOrder/takeoutOrder.js
const common = require('../../../public.js')
Page({

    /**
     * 页面的初始数据
     */
    data: {
        aa:799,
        height: '',
        top: '',
        num: 2,
        showOrder: false,
        showCancel: false,
        cansselList: [
            ' 修改订单信息',
            '狠心取消'
        ],
        time: 15 * 60 * 1000,
        timeData: {},
        orderId: '',
        orderList: [], //商品数组
        moreGood: false,
        remark: '',
        items: [],
        receiverAddress: '',
        receiverMobile: '',
        handCansel:true , //主动取消

    },
    time(time) {
        if (!time) {
            return '-'
        }
        return common.dateFormat('yyyy-MM-dd HH:mm:ss', time)
    },
    // 备注
    remarkInput(e) {
        this.setData({
            remark: e.detail.value
        })
    },
    // 手机号 :'',
    remarkReceiverMobile(e) {
        console.log(e, "jjjooopppppp")
        this.setData({
            receiverMobile: e.detail.value
        }, () => {

        })
    },
    remarkReceiverAddress(e) {
        this.setData({
            receiverAddress: e.detail.value
        }, () => {
            console.log(this.data.receiverAddress, "osososooso")
        })
    },
    // 去评价
    toComment(e) {
        const item = e.currentTarget.dataset.item
        wx.navigateTo({
          url: '/pages/comment/index?orderId=' + item.orderId,
        })
      },
    submitChange() {
        const that = this
        let items = []
        this.data.orderList.map((item, index) => {
            console.log(item, "1111111")
            items.push({
                dishFlavor: item.dishFlavor,
                itemId: item.itemId,
                num: item.num,
                title: item.title,
                price: item.price,
                totalFee: (item.num * item.price),
                picPath: item.picPath,
            })
        })
        this.setData({
            items
        }, () => {
            that.normalPayFunc()
        })
    },
    checkTime(i) {
        if (i < 10) {
            i = "0" + i;
        }
        return i;
    },

    timeFn(locksecends) {
       const that = this
        var djsendtime = wx.getStorageSync('djsendtime') //结束时间
        if (djsendtime == null || djsendtime == undefined || djsendtime == 'undefined' || djsendtime == 'null' || djsendtime == '') {
            var now = new Date().getTime(); //当前时间戳
            var endtime = locksecends * 1000 + now; //结束时间戳
            wx.setStorageSync('djsendtime', endtime); //将结束时间保存到cookie
        }
        let timerss = setInterval(function () {
            locksecends--;
            console.log(locksecends, "8888888888888")
            if (locksecends <= 0) {
                console.log("刷新页面")
                //倒计时结束清除 localStorage值
                wx.removeStorageSync("djsendtime");
                clearInterval(timerss);
                that.setData({
                    handCansel:false
                },()=>{
                    // that.cancelOrder()
                })
               
                // that.totoalFn(that.data.objss)
            } else {

            }
        }, 1000)

       

        return timerss
    },

    getOrderDes: function () {
        var that = this;
        this.setData({
            isLoading: true
        })
        common.post('/order/getOrderDetail', {
            userId: that.data.userInfo.id,
            orderId: that.data.orderId,
            token: that.data.token
        }, function (responseData) {
            if (responseData && responseData.status === 200) {
                console.log(responseData.data, "445566625555566s")

                responseData.data[0].postFee = parseFloat(responseData.data[0].postFee)
                responseData.data[0].totalFee = parseFloat(responseData.data[0].totalFee)
                responseData.data[0].payment = parseFloat(responseData.data[0].payment)
                let totlal = responseData.data[0].postFee + responseData.data[0].totalFee
                let totalPayment = (totlal - (responseData.data[0].goldPrice / 100) - responseData.data[0].discountMoney).toFixed(2)

                
                that.setData({
                    totalPayment,
                    finalPayMent:responseData.data[0].payment + responseData.data[0].postFee,
                    orderList: responseData.data,
                    moreGood: responseData.data.length > 2 ? true : false,
                    receiverAddress: responseData.data[0].receiverAddress,
                    receiverMobile: responseData.data[0].receiverMobile
                })
              

                for (let i = 0; i < responseData.data.length; i++) {
                    if (responseData.data[i].orderId == that.data.orderId) {
                        const orderTime = that.time(responseData.data[i].orderCreated)
                        const paymentTime = that.time(responseData.data[i].paymentTime)
                        that.setData({
                            orderTime,
                            paymentTime,
                            orderDes: responseData.data[i], //订单信息
                        }, () => {
                            wx.setNavigationBarTitle({
                                title: that.data.title, //页面标题为路由参数
                            })
                        })
                    }
                    // 获取店铺信息
                    // that.getStoreInfo(responseData.data[i].storeId)
                    break
                }
            } else {
                common.showRequestErrMsg(responseData)
            }
        },
            function () {
                that.setData({
                    isLoading: false
                })
            }
        )
    },

    // 修改订单信息
    normalPayFunc() {
        const that = this
        const tempJson = {
            orderId: parseInt(that.data.orderId),
            receiverAddress: that.data.receiverAddress,
            receiverMobile: that.data.receiverMobile,
            remark: that.data.remark
        };
        var url = '/order/updateOrderShipping'
        common.post(url, tempJson, function (ret) {
            if (ret.status == 200) {
                // console.log(ret, "jjjjjjj")
                common.showToast('修改完成')
                that.setData({
                    showOrder: false,
                    loadingCount: that.data.loadingCount + 1
                }, () => {
                    that.getOrderDes()
                })

            } else {
                common.showRequestErrMsg(ret)
            }
        }, function () {
            that.setData({
                loadingCount: that.data.loadingCount - 1
            })
        })
    },
    // 去支付
    go_pay() {
        const that = this
        const tempJson = {
            userId: that.data.userInfo.id,
            token: that.data.token,
            orderId: that.data.orderId,
            // openid: that.data.openid,
            xcxOpenid: that.data.openid,
        }
       
        // common.wxPayRequest('/wxxcxPayForGoods', tempJson, function (res) {
               common.wxPayRequest('/wxxcxPayGoodsForChinaUms', tempJson, function (res) {
            if (res.status === 200) {
                //微信支付
                wx.requestPayment({
                    'timeStamp': res.data.timeStamp,
                    'nonceStr': res.data.nonceStr,
                    'package': res.data.package,
                    'signType': res.data.signType,
                    'paySign': res.data.paySign,
                    'success': function (res) {

                        that.reloadData()
                    },
                    'fail': function (res) {

                        if (res.errMsg === 'requestPayment:fail cancel') {
                        } else {
                            common.showToast(res.errMsg)
                        }
                    }
                })
            }
        })
    },
    onChangeTime(e) {
        this.setData({
            timeData: e.detail,
        });
    },
    click_order(e) {
        let index = e.currentTarget.dataset.item
        switch (index) {
            case 0:
                this.setData({ showOrder: true, showCancel: false })
                break;
            case 1:
                // this.cancelOrder()
                break;
            default:
        }
    },
    cancelOrder() { // 取消订单
        const that = this
        // common.showAlertView('提示', '是否取消该订单', function (res) {
        //     if (res) {
     
        let tempJson = {
            userId: that.data.userInfo.id,
            token: that.data.token,
            orderId: that.data.orderId
        }
        common.post('/order/cancel', tempJson, function (res) {
            if (res.status === 200) {
                 var url;
                // 判断被动还是主动
                if(that.data.handCansel){
                   url =`/packageC/pages/takeoutCansel/takeoutCansel?orderId=${that.data.orderId}`
                }else{
                    url =`/packageC/pages/takeoutCanselDetail/takeoutCanselDetail?orderId=${that.data.orderId}`
                }
                wx.redirectTo({
                    url ,
                })
                // that.reloadData()
            } else {
                common.showRequestErrMsg(res)
            }
        })
        //     }
        // })
    },
    onCloseOder() {
        this.setData({
            showOrder: false
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        const that = this
        //获取胶囊位置
        clearInterval(that.timeFn())
        let capsule = wx.getMenuButtonBoundingClientRect()
        this.setData({
            height: capsule.height,
            top: capsule.top,
        })
        common.getLocalUserInfo(function (success, data) {
            if (success) {
                that.setData({
                    userInfo: data.user,
                    token: data.token,
                    openid: data.openid,
                    orderId: options.orderId ? options.orderId : '176743'
                }, function () {
                    that.getOrderDes()
                })
            }
        }, true)
    },
    cancel_order() {
        this.setData({
            showCancel: true
        })
    },
    xiugai_order() {
        this.setData({ showOrder: true });
    },
    onClose() {
        this.setData({ showCancel: false });
    },
    // 查看更多
    click_lenght() {
        this.setData({
            moreGood: false
        })
    },
    // 修改订单信息
    revise_order() {
        this.setData({
            showOrder: true
        })
    },
    goBack(){
        wx.navigateBack({
            delta: 1,
          })
    },
    onUnload() {
        clearInterval(this.timeFn())
    },

})